/*
 * busconsole_client.c
 *
 *  Created on: 18/feb/2011
 *      Author: ivano
 */

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/errno.h>

#include "../terminals.h"

terminal_t* term;

void help(int output);
void parse(char* cmd, int output);

int main(int argc, char* argv[]) {
	int res, sock = -1;
	struct sockaddr_un my_addr;
	socklen_t peer_addr_size;
	fd_set fds;
	char buffer[4096];
	char* res_str;

	if (argc != 2) {
		fprintf(stderr, "Uso: %s unix_socket_path\n", argv[0]);
		return 1;
	}

	setvbuf(stdout,NULL,_IONBF,0);

	if (sock == -1) {
		sock = socket(AF_UNIX, SOCK_STREAM, 0);
		if (sock == -1) {
			fprintf(stderr, "ERROR: busconsole: socket() failed: unable to create local UNIX socket (errno: %d)\n", errno);
			return errno;
		}
	}

	memset(&my_addr, 0, sizeof(struct sockaddr_un));

	my_addr.sun_family = AF_UNIX;
	strncpy(my_addr.sun_path, argv[1], sizeof(my_addr.sun_path) - 1);

	//connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr))
	if (connect(sock, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_un)) == -1) {
		fprintf(stderr, "ERROR: connect() failed: unable to connect to local UNIX socket %s (errno: %d)\n", argv[1], errno);
		fprintf(stderr, "ERROR: -> %s\n", strerror(errno));
		return errno;
	}

	// Starting terminal
	buffer[4095] = 0;

	term = terminal_new();
	close(term->pins.terminal_read);
	close(term->pins.terminal_write);
	close(term->pins.daemon_read);
	close(term->pins.daemon_write);
	term->pins.terminal_read = sock;

	while (1) {
		FD_ZERO(&fds);
		FD_SET(sock, &fds);
		FD_SET(0, &fds);

		printf("\e[1;31m$ \e[0m");

		res = select ((sock > 0 ? sock : 0) + 1, &fds, NULL, NULL, NULL);
		if (res == -1) {
			fprintf(stderr, "ERROR: busconsole: select() failed: exiting\n");
			return 1;
		}

		if (FD_ISSET(0, &fds)) {
			res = read(0, buffer, 4095);
			if (res <= 0) {
				fprintf(stderr, "INFO: read() read nothing: exiting\n");
				return 0;
			}
			parse(buffer, 1);
			res = write(sock, buffer, res);
			if (res <= 0) {
				fprintf(stderr, "INFO: connection closed: exiting\n");
				return 0;
			}
		}
		if (FD_ISSET(sock, &fds)) {
			do {
				res_str = terminal_read_from_daemon(term);
				if (res_str == NULL) {
					fprintf(stderr, "INFO: connection closed: exiting\n");
					return 0;
				}
				printf("\b\b\e[0;32m%s\e[0m\n", res_str);
				free(res_str);
			} while (terminal_has_more_for_terminal(term));
		}
	}
}

void parse(char* cmd, int output) {
	if (!strncmp(cmd, "exit", 4))
		exit(0);
	else if (!strncmp(cmd, "help", 4))
		help(output);
}

void help(int output) {
	printf(" * exit\n");
}
